/**
 * 百度地图 JavaScript API v3.0 交通流量图层
 *
 * @开源库类参考 TrafficControl
 * http://api.map.baidu.com/library/TrafficControl/1.2/docs/help.html
 *
 * @类参考 TrafficLayer
 * https://mapopen-pub-jsapi.bj.bcebos.com/jsapi/reference/jsapi_reference_3_0.html#a6b2
 *
 * @DEMO 是百度地图2.0的demo, 3.0未找到
 * https://lbsyun.baidu.com/jsdemo.htm#g0_3
 */

import { onBeforeUnmount, shallowRef, watch } from 'vue';
import { resolveUnref, resolveRef } from '@vueuse/core';

/**
 *
 * @param {*} map 地图实例  MaybeComputedRef<T> | MaybeRef<T> | T
 * @param {*} visible 是否显示流量图层 MaybeComputedRef<boolean> | MaybeRef<boolean> | boolean
 * @param {*} controlAnchor 控件位置 MaybeComputedRef<T> | MaybeRef<T> | T https://mapopen-pub-jsapi.bj.bcebos.com/jsapi/reference/jsapi_reference_3_0.html#a2b1
 * @returns
 */
export function useMapTraffic({ map, visible, controlAnchor }) {
  const trafficControl = shallowRef(null);

  const setTrafficControl = () => {
    const mapValue = resolveUnref(map);
    const visibleValue = resolveUnref(visible);
    // 没有地图无法添加图层
    if (!mapValue) return;

    if (!trafficControl.value) {
      trafficControl.value = new window.BMapLib.TrafficControl({
        showPanel: false, //是否显示路况提示面板
      });

      mapValue.addControl(trafficControl.value);

      // 将设置面板移动到body中，防止zIndez被覆盖
      const tcWrap = document.querySelector('#tcWrap');
      tcWrap.parentElement.removeChild(tcWrap);
      tcWrap.style.zIndex = 9999;
      document.querySelector('body').append(tcWrap);

      // 隐藏TrafficControl带的按钮，使用其它按钮触发
      document.querySelector('#tcBtn').style.display = 'none';
    }

    trafficControl.value.setAnchor(resolveUnref(controlAnchor) || window.BMAP_ANCHOR_BOTTOM_RIGHT);
    visibleValue
      ? trafficControl.value.showTraffic({
          predictDate: {
            hour: 11,
            weekday: 3,
          },
        })
      : trafficControl.value.hideTraffic();
  };

  /**
   *
   * @param {e} e ClickEvent
   */
  const showTrafficPannel = (e) => {
    // 触发TrafficControl的按钮事件
    document.querySelector('#tcBtn').click();
    const tcWrap = document.querySelector('#tcWrap').style
    tcWrap.bottom = 'unset';
    const rect = e?.currentTarget?.getBoundingClientRect();
    if(rect) {
      tcWrap.top = `${rect.top + rect.height + 4}px`;
      tcWrap.right = `${window.innerWidth - rect.right}px`;
    }
  };

  const removeTrafficControl = () => {
    const mapValue = resolveUnref(map);
    mapValue?.removeControl?.(trafficControl.value);
  };

  watch(
    [resolveRef(map), resolveRef(visible), resolveRef(controlAnchor)],
    () => {
      setTrafficControl();
    },
    { immediate: true },
  );

  onBeforeUnmount(() => {
    removeTrafficControl();
  });

  return {
    trafficControl,
    showTrafficPannel,
    removeTrafficControl,
  };
}
